<template>
  <h1 style="color: orange">{{content.id==null?'发布内容页面':'修改内容页面'}}</h1>
  <el-form label-width="100px">
    <el-form-item label="文章标题">
      <el-input placeholder="请输入文章标题" v-model="content.title"></el-input>
    </el-form-item>
    <el-form-item label="文章类型">
      <el-radio-group :disabled="content.id!=null" @change="typeChange()" v-model="content.type">
        <el-radio-button :label="c.type"
                         v-for="c in catTypeArr">
          {{c.name}}
        </el-radio-button>

      </el-radio-group>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select v-model="content.categoryId" placeholder="请选择">
        <el-option v-for="c in categoryArr"
                   :label="c.name" :value="c.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="封面">
<!--    id不为null代表是修改  -->
      <img v-if="content.id!=null&&fileList.length==0"
           :src="'http://localhost:8080'+content.imgUrl"
           style="width: 145px;height: 145px">
      <!--   上传组件开始   -->
      <el-upload
          v-model:file-list="fileList"
          action="http://localhost:8080/v1/upload"
          name="file"
          limit="1"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--   上传组件结束   -->
    </el-form-item>
    <el-form-item v-show="content.type==2" label="视频">
      <video v-if="content.id!=null&&videoList.length==0"
      :src="'http://localhost:8080'+content.videoUrl"
      style="width: 200px" type="video/mp4" controls></video>
      <!--   上传组件开始   -->
      <el-upload
          v-model:file-list="videoList"
          action="http://localhost:8080/v1/upload"
          name="file"
          limit="1"
          accept="video/*"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
        <el-button>点击上传视频</el-button>
        <div>只能上传mp4文件,且不超过100MB</div>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--   上传组件结束   -->
    </el-form-item>
    <el-form-item v-show="content.type!=2" label="文章内容">
      <div ref="editorDiv"></div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="post()">{{content.id==null?'发布内容':'修改内容'}}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import { Plus } from '@element-plus/icons-vue'
//导入富文本编辑器    安装指令: npm install wangeditor
import Editor from 'wangeditor';
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";
import router from "@/router";

const videoList = ref([]);
const post = ()=>{
  let user = localStorage.user?JSON.parse(localStorage.user):null;
  if (user==null){
    alert("请先登录!");
    router.push('/login');
    return;
  }
  content.value.userId= user.id;

  if (content.value.title.trim()==''){ElMessage.error("请输入标题!");return;}
  if (content.value.categoryId==''){ElMessage.error("请选择二级分类");return;}
  if (content.value.id==null){//发布
    if (fileList.value.length==0){ElMessage.error("请选择封面!");return;}
    //把上传成功的图片路径装进content对象
    let imgUrl = fileList.value[0].response.data;
    content.value.imgUrl = imgUrl;
  }else{//修改
    if (fileList.value.length>0){//修改了图片
      let imgUrl = fileList.value[0].response.data;
      content.value.imgUrl = imgUrl;
    }
  }

  if (content.value.type==2){//视频
    if (content.value.id==null){//发布
      if (videoList.value.length==0&&content.value.id==null){ElMessage.error("请上传视频文件!");return;}
      let videoUrl = videoList.value[0].response.data;
      content.value.videoUrl = videoUrl;
    }else{//修改
      if (videoList.value.length>0){
        let videoUrl = videoList.value[0].response.data;
        content.value.videoUrl = videoUrl;
      }
    }
  }else{//食谱或资讯
    //设置文章内容
    content.value.content = editor.txt.html();
//设置文章摘要  从文章内容的纯文本内容中截取前30个字符
    content.value.brief = editor.txt.text().slice(0,30);
  }


  //发请求
  let data = qs.stringify(content.value);
  axios.post('http://localhost:8080/v1/contents/add-new',data)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success(content.value.id==null?'发布完成!':'修改完成!');
      if (localStorage.from!=null&&localStorage.from=='admin'){
        router.push('/admin/content');//后台管理的页面
        localStorage.from=null;
      }else{
        router.push('/personal/management');//进入稿件管理页面
      }
    }
  })


}

const content = ref({title:'',type:'1',categoryId:''})

const catTypeArr = ref([]);
const categoryArr = ref([]);

const typeChange = ()=>{
  content.value.categoryId='';
  //发请求获取二级分类的数据
  axios.get('http://localhost:8080/v1/categories/'
      +content.value.type+'/sub')
      .then((resposne)=>{
        if (resposne.data.code==2001){
          categoryArr.value = resposne.data.data;
        }
      })
}
onMounted(()=>{
  if (location.search.includes('id')){
    let id = new URLSearchParams(location.search).get('id');
    axios.get('http://localhost:8080/v1/contents/'+id+"/update")
    .then((response)=>{
      if (response.data.code=2001){
        content.value = response.data.data;
        //让富文本编辑器显示文章内容
        editor.txt.html(content.value.content);
        //重新请求当前content对象中type对应的二级分类
        //发请求获取二级分类的数据
        axios.get('http://localhost:8080/v1/categories/'
            +content.value.type+'/sub')
            .then((resposne)=>{
              if (resposne.data.code==2001){
                categoryArr.value = resposne.data.data;
              }
            })

      }
    })
  }

  //发请求获取二级分类的数据
  axios.get('http://localhost:8080/v1/categories/1/sub')
  .then((resposne)=>{
    if (resposne.data.code==2001){
      categoryArr.value = resposne.data.data;
    }
  })

  axios.get('http://localhost:8080/v1/categories/type')
  .then((response)=>{
    if (response.data.code==2001){
      catTypeArr.value = response.data.data;
    }
  })
})


const editorDiv = ref(null);//此变量指向页面中的div(这个div用来装富文本编辑器组件)
let editor = null;
//onMounted是VUE生命周期方法(指VUE实例从创建到销毁过程中 自动调用的方法)
onMounted(()=>{//Vue实例和页面元素挂载完成后执行
  editor = new Editor(editorDiv.value);
  editor.config.placeholder = "请输入内容详情....";
  editor.create();
})




const fileList = ref([]);
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove = (uploadFile, uploadFiles) => {
  //得到删除图片的路径
  let imgUrl = uploadFile.response.data;
  //发出删除文件的请求
  axios.post('http://localhost:8080/v1/remove?imgUrl='+imgUrl)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success("服务器文件删除完成!");
    }
  })
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
</script>

<style scoped>

</style>